var data;
$(document).ready(function() {
    $.getJSON("catalogue.json", function(result) {
        data = result;
        init();
    });

    // var xhr = new XMLHttpRequest();
    // xhr.open('get', 'https://v1.jinrishici.com/all.json');
    // xhr.onreadystatechange = function () {
    //     if (xhr.readyState === 4) {
    //         var data = JSON.parse(xhr.responseText);
    //         var gushici = document.getElementById('content_mid');
    //         gushici.innerText = data.content;
    //     }
    // };
    // xhr.send();
});

function init() {
    $.each(data, function(i, field) {
        $(".top ul").append("<li><a onClick=\"javascript:updateNav('" + i + "');\">" + field.top_name + "</a></li>");
    });
    // updateNav("0");
}

function updateNav(ind) {
    $(".navlist").empty();
    $.each(data[ind]["pages"], function(i, field) {
        $(".navlist").append("<a onClick=\"javascript:toHtml('" + data[ind].dir + "/" + field.url + "');\">" + field.name + "</a>");
    });
    toHtml(data[ind].dir + "/" + data[ind]["pages"][0]["url"])
}

function toHtml(url) {
    url = encodeURI(url);
    $("#content_mid").load(url, function(responseTxt, statusTxt, xhr) {
        if (statusTxt == "success") {
            var converter = new showdown.Converter({
                tables: true,
                ghCodeBlocks: true
            });
            markdownText = converter.makeHtml(responseTxt).replace(/<pre><code>/g, "<pre><code class='language-css'>");
            // document.getElementById('test').innerHTML= markdownText;
            document.getElementById('content_mid').innerHTML = markdownText;
        } else if (statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
}